<template>
  <el-card>
    <!-- 标题 + 新增 -->
    <template #header>
      <div class="flex-between">
        <span>常数类别管理</span>
        <el-button type="primary" @click="openDialog">新增类别</el-button>
      </div>
    </template>

    <!-- 列表 -->
    <el-table :data="list" stripe border style="width: 100%" :loading="loading">
      <el-table-column prop="code" label="编码" width="120" />
      <el-table-column prop="name" label="名称" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="onEdit(row.id)"
          >编辑</el-button
          >
          <el-button type="danger" size="small" @click="onDelete(row.id)"
          >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增 / 编辑 对话框 -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="480px"
        @open="onDialogOpen"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入编码" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="onSubmit"
        >确定</el-button
        >
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import request from '@/utils/request'
import { ElMessageBox, ElMessage } from 'element-plus'

interface Item {
  id: number
  code: string
  name: string
}

const list = ref<Item[]>([])
const loading = ref(false)
const submitting = ref(false)

async function loadData() {
  loading.value = true
  try {
    const { data } = await request.get('/api/master/constant/type/list')
    list.value = data.map((r: any) => ({
      id: r.id ?? r.constanttypeid, // 兼容不同字段名
      code: r.constanttypecode,
      name: r.constanttypename,
    }))
  } catch {
    ElMessage.error('加载列表失败')
  } finally {
    loading.value = false
  }
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

interface FormModel {
  code: string
  name: string
}
const form = reactive<FormModel>({ code: '', name: '' })
const rules = {
  code: [{ required: true, message: '请输入编码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
}
let editId: number | null = null
const formRef = ref<InstanceType<typeof import('element-plus').ElForm>>()

function openDialog() {
  editId = null
  dialogTitle.value = '新增类别'
  form.code = ''
  form.name = ''
  dialogVisible.value = true
}

function closeDialog() {
  dialogVisible.value = false
}

function onDialogOpen() {
  formRef.value?.clearValidate()
}

async function onEdit(id: number) {
  loading.value = true
  editId = id
  dialogTitle.value = '编辑类别'
  try {
    const res = await request.get(`/api/master/constant/type/getById/${id}`)
    const record = res.data || res
    form.code = record.constanttypecode
    form.name = record.constanttypename
    dialogVisible.value = true
    formRef.value?.clearValidate()
  } catch {
    ElMessage.error('获取详情失败')
  } finally {
    loading.value = false
  }
}

async function onDelete(id: number) {
  try {
    await ElMessageBox.confirm('确认删除？', '提示', { type: 'warning' })
    await request.delete(`/api/master/constant/type/deleteById/${id}`)
    ElMessage.success('删除成功')
    loadData()
  } catch (err: any) {
    if (err !== 'cancel') ElMessage.error(err.message || '删除失败')
  }
}

async function onSubmit() {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
  } catch {
    return
  }
  submitting.value = true
  const payload: any = {
    constanttypecode: form.code,
    constanttypename: form.name,
  }
  if (editId !== null) payload.id = editId
  try {
    await request.post('/api/master/constant/type/saveOrUpdate', payload)
    ElMessage.success(editId !== null ? '更新成功' : '新增成功')
    dialogVisible.value = false
    loadData()
  } catch {
    ElMessage.error(editId !== null ? '更新失败' : '新增失败')
  } finally {
    submitting.value = false
  }
}

onMounted(loadData)
</script>

<style scoped>
.flex-between {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
